package com.fc.advbox.controller.admin;

import com.fc.advbox.common.ResponseJson;
import com.fc.advbox.dto.admin.InvestorAssetReqDto;
import com.fc.advbox.entity.AdvUserEntity;
import com.fc.advbox.entity.InvestorAcctEntity;
import com.fc.advbox.entity.InvestorAssetEntity;
import com.fc.advbox.service.IInvestorAcctService;
import com.fc.advbox.service.IInvestorAssetService;
import com.fc.advbox.utils.Constant;
import com.fc.advbox.utils.DateTimeHelper;
import com.fc.advbox.utils.R;
import com.fc.advbox.utils.annotation.SysLog;
import com.fc.advbox.utils.validator.ValidatorUtils;
import com.fc.advbox.utils.validator.group.AddGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Description: admin API for investor asset manager
 * User: Charles.Gao
 * Date: 2018-07-11 14:56
 */
@RestController
@RequestMapping("/api/admin/asset")
@Api(value="管理端-维护投资者资产相关的API", tags={"投资者资产管理接口"})
public class AssetAdminController {
    private final IInvestorAssetService assetService;

    private final IInvestorAcctService acctService;

    @Autowired
    public AssetAdminController(IInvestorAssetService assetService, IInvestorAcctService acctService){
        this.assetService = assetService;
        this.acctService = acctService;
    }

    /**
     * 创建资产
     */
    @ApiOperation(value = "POST Create Asset 创建投资者资产。仅超级管理员可调用。需要先获取userId",
            notes = " REST 方式登录。" +
                    "使用方式: <ul>" +
                    "<li><i>userId 用户ID</i></li>" +
                    "<li><i>assetName 资产名称</i></li>" +
                    "<li><i>amount 金额</i></li>" +
                    "<li><i>interestPerYear ：年化利率</i></li>" +
                    "<li><i>durationMonth ： 产品周期</i></li>" +
                    "</ul>",
            response = R.class,
            httpMethod = "POST",
            consumes = "application/json",
            produces = "application/json",
            code = 200
    )
    @SysLog("新建投资者资产")
    @PostMapping("/save")
    @RequiresPermissions("admin:asset")
    public ResponseJson save(@RequestBody InvestorAssetReqDto asset){
        ValidatorUtils.validateEntity(asset);
        List<InvestorAcctEntity> acctList = acctService.queryInvestorAcctByUserId(asset.getUserId());
        if(null == acctList || acctList.size() == 0){
            return ResponseJson.error(ResponseJson.BAD_REQUEST, "用户或者账户不存在");
        }

        //取第一个CASH账户
        InvestorAcctEntity acct = new InvestorAcctEntity();
        for(InvestorAcctEntity a: acctList){
            if(Constant.AcctType.CASH.getValue().equals(a.getType())){
                acct = a;
                break;
            }
        }

        InvestorAssetEntity assetEntity = new InvestorAssetEntity();
        assetEntity.setAmount(asset.getAmount());
        assetEntity.setAssetName(asset.getAssetName());
        assetEntity.setBalance(asset.getAmount());
        assetEntity.setBuyTime(asset.getBuyTime());
        assetEntity.setStartTime(DateTimeHelper.addDays(asset.getBuyTime(),1));
        assetEntity.setEndTime(DateTimeHelper.addMonth(assetEntity.getStartTime(),asset.getDurationMonth()));
        assetEntity.setInterestPerDay(asset.getInterestPerYear().divide(new BigDecimal(360),5,BigDecimal.ROUND_HALF_DOWN));
        assetEntity.setInterestPerMonth(asset.getInterestPerYear().divide(new BigDecimal(12),4,BigDecimal.ROUND_HALF_DOWN));
        assetEntity.setInterestPerYear(asset.getInterestPerYear());
        assetEntity.setUserId(asset.getUserId());
        assetEntity.setStatus(Constant.AssetStatus.ACTIVE.getValue());
        assetEntity.setAcctId(acct.getId());
        assetEntity.setRedeemTime(null);
        this.assetService.save(assetEntity);
        return ResponseJson.success();
    }

    @ApiOperation(value = "POST 投资者资产赎回。仅超级管理员可调用",
            notes = " REST 方式登录。" +
                    "使用方式: <ul>" +
                    "<li><i>assetId 资产ID</i></li>" +
                        "</ul>",
            response = R.class,
            httpMethod = "POST",
            consumes = "application/json",
            produces = "application/json",
            code = 200
    )
    @SysLog("投资者赎回资产")
    @PostMapping("/redeem/{assetId}")
    @RequiresPermissions("admin:asset")
    public ResponseJson redeem(@PathVariable("assetId") Long assetId){
        InvestorAssetEntity assetEntity = assetService.queryObject(assetId);
        if(null == assetEntity){
            return ResponseJson.error(ResponseJson.BAD_REQUEST, "资产不存在");
        }
        assetEntity.setAmount(new BigDecimal(0));
        assetEntity.setBalance(new BigDecimal(0));
        assetEntity.setStatus(Constant.AssetStatus.REDEEMED.getValue());
        assetEntity.setRedeemTime(new Date());
        this.assetService.update(assetEntity);
        return ResponseJson.success();
    }
}
